package com.android.openapp.ui;

import java.util.ArrayList;

import com.android.openapp.data.Place;
import com.android.openapp.services.Controller.ControllerBinder;
import com.android.openapp.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

/**
 * Fragment che gestisce la visualizzazione di una lista di luoghi
 * @author Simone Panza
 *
 */
public class PlacesListFragment extends ListFragment implements FragmentInteract{
	//ArrayAdapter<String> la;
	LocationAdapter locadapter;
	SimpleCursorAdapter mAdapter;
	
	MainActivity mActivity;
	Button mButRefresh;
	Button mButSearch;
	
	/**
	 * empty constructor, as requested from Android documentation
	 */
	public PlacesListFragment(){
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.places_list, container, false);
		
		mButRefresh = (Button) v.findViewById(R.id.button_list_refresh);
		mButSearch = (Button) v.findViewById(R.id.button_list_search);
		//tasto refresh
		mButRefresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(MainActivity.TAG,"tasto refresh");
				if(mBinder!=null)
					updateNearPlaces();
			}
		});
		
		//tasto search
		mButSearch.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.d("search","onClick()");
				Boolean l=mActivity.onSearchRequested();
				Log.d("search",Boolean.toString(l));
					
			}
		});
		
		return v;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.v(MainActivity.TAG, "PlacesListFragment.onActivityCreated()");
		
		mActivity = (MainActivity) getActivity();
		mActivity.setCurrentFragment(this);
		//prendo il binder ogni volta dalla MainActivity
		mBinder = mActivity.mBinder;
		
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, 
					int position, long id) {
				//Place p = (Place) parent.getAdapter().getItem(position);
				showPlaceInfo(getActivity(), R.layout.place_info, position);
				//Toast.makeText(getActivity(), p.getDenominazione(), Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	@Override
	public void onStart() {
		super.onStart();
		//aggiorno la view
		updateListPlaces();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.v(MainActivity.TAG, "PlacesListFragment.onDestroy()");
	}
	
	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		
		Log.v(MainActivity.TAG, "PlacesListFragment.onCreate()");
	}
	
	@Override
	public void onAttach(Activity arg0) {
		super.onAttach(arg0);
		Log.v(MainActivity.TAG, "PlacesListFragment.onAttach()");
	}
	
	ControllerBinder mBinder;
	
	void showPlaceInfo(final Context context, int resource, final int placeListIndex) {
		Place place = Place.lista.get(placeListIndex);
		// preparo la view da visualizzare nel Dialog
		//final Context mAppContext = context.getApplicationContext();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(resource, null);
        String title = place.getDenominazione();
        //UI elements
        TextView tipo = (TextView)layout.findViewById(R.id.tipo);
        TextView indirizzo = (TextView)layout.findViewById(R.id.indirizzo);
        tipo.setText(place.getTipologia());
        indirizzo.setText(place.getAddress());
        TextView contatti = (TextView) layout.findViewById(R.id.contatti);
        String cInfo = place.getContactInfo();
        if(cInfo != null)
        	contatti.setText(cInfo);
        
        // costruisco il Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(layout).setIcon(android.R.drawable.ic_dialog_info).
		setTitle(title).setCancelable(true)
			.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				});
		final AlertDialog dialog = builder.create();
		dialog.show();
		
		//coordinate
		final Double lat = place.getLatitude();
		final Double lon = place.getLongitude();
		
		//bottone per passare alla mappa
        Button mapButton = (Button) layout.findViewById(android.R.id.button1);
        mapButton.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				if(lat != null && lon != null){
					
					Intent i = new Intent(MainActivity.VIEW_MAP_TAB);
					i.putExtra("latitude", lat);
					i.putExtra("longitude", lon);
					i.putExtra("index", placeListIndex);
					v.getContext().sendBroadcast(i);
					dialog.dismiss();
				}
				else {
					String text = context.getResources().getString(R.string.noaddressfound);
					Utils.showToast(context, text);
				}
			}
        	
        });
	}
	
	/**
	 * Richiede una nuova lista di places, ordinata in base alla distanza dalla location corrente
	 */
	public void updateNearPlaces(){
		Log.v(MainActivity.TAG, "requesting near places");
		
		mBinder.getNearPlaces();
		
		//locadapter= new LocationAdapter(mActivity, R.layout.locationlist, list);
		//la = new ArrayAdapter<String>(mActivity, R.layout.entry ,list);
		//setListAdapter(locadapter);
	}
	
	/**
	 * Aggiorna la view, prendendo la lista disponibile
	 */
	public void updateListPlaces(){
		Log.v(MainActivity.TAG, "updating list view");
		ArrayList<Place> list = (ArrayList<Place>) Place.lista;
		locadapter= new LocationAdapter(mActivity, R.layout.locationlist, list);
		//la = new ArrayAdapter<String>(mActivity, R.layout.entry ,list);
		setListAdapter(locadapter);
	}
	
	/**
	 * called when the onServiceConnected() method in the Activity is called
	 */
	@Override
	public void onBind(ControllerBinder binder) {
		
		mBinder = binder;
		// TODO do other stuff... maybe updateNearLocations
		updateNearPlaces();
	}

	@Override
	public void onDataReceived() {
		// TODO Auto-generated method stub
		updateListPlaces();
	}

	@Override
	public void onLocationReceived(int listIndex) {
		// do nothing
	}

	@Override
	public void onSearchCompleted() {
		updateListPlaces();
	}
}
